<script setup lang="ts">
import { ref, computed } from 'vue'
import Calendar from './Calendar.vue'
import Popover from './Popover.vue'
import Button from './Button.vue'
import { CalendarIcon } from 'lucide-vue-next'
import { cn } from '@/lib/utils'
import type { DateValue } from '@internationalized/date'

interface Props {
  modelValue?: Date | null
  placeholder?: string
  class?: string
  disabled?: boolean
}

const props = withDefaults(defineProps<Props>(), {
  placeholder: '选择日期',
  modelValue: null
})

const emits = defineEmits<{
  'update:modelValue': [value: Date | null]
}>()

const open = ref(false)

const value = computed({
  get: () => {
    if (!props.modelValue) return undefined
    return {
      year: props.modelValue.getFullYear(),
      month: props.modelValue.getMonth() + 1,
      day: props.modelValue.getDate()
    } as DateValue
  },
  set: (val) => {
    if (!val) {
      emits('update:modelValue', null)
    } else {
      const date = new Date(val.year, val.month - 1, val.day)
      emits('update:modelValue', date)
      open.value = false
    }
  }
})

const displayValue = computed(() => {
  if (!props.modelValue) return props.placeholder
  return props.modelValue.toLocaleDateString('zh-CN', { 
    year: 'numeric', 
    month: 'long', 
    day: 'numeric' 
  })
})
</script>

<template>
  <Popover v-model:open="open" :modal="true">
    <template #trigger>
      <Button
        variant="outline"
        :class="cn(
          'w-full justify-start text-left font-medium',
          !modelValue && 'text-gray-400',
          props.class
        )"
        :disabled="disabled"
      >
        <CalendarIcon class="mr-2 h-4 w-4 opacity-70" />
        <span class="text-[13px]">{{ displayValue }}</span>
      </Button>
    </template>
    <Calendar
      v-model="value"
      :locale="'zh-CN'"
      :initial-focus="true"
      class="w-[300px]"
    />
  </Popover>
</template>

